<?php
namespace Destroyer\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

use Destroyer\Models\User;

class UserController extends Controller
{

	/**
	 * @path /api/system/user
	 */
	public function index(Request $request)
	{
		$validated = $request->validate([
			// 分页
			'page'      => 'sometimes|integer|min:1',
			'page_size' => 'sometimes|integer|between:1,100',
			// 排序
			'sorter'           => 'sometimes|array:field,direction',
			'sorter.direction' => 'sometimes|string|in:ascend,descend',
			'sorter.field'     => 'sometimes|string|in:id,created_at,login_time',
			// 筛选
			'filters.status'        => 'sometimes|array|size:1',
		]);

		$query = User::query();

		// 筛选
		if( Arr::has($validated, 'filters.status') ){
			$value = Arr::get($validated, 'filters.status.0');
			$query->where('status', $value);
		}

		// 排序
		$field = Arr::get($validated, 'sorter.field', 'id');
		$direction = Arr::get($validated, 'sorter.direction', 'descend');
		$query->orderBy($field, substr($direction, 0, -3));

		// 查询
		$page_size = $request->input('page_size');
		$models = $query->paginate($page_size);

		return response()->admin($models);
	}

	public function store(Request $request)
	{
		$model = User::findOrFail($id);

		$model->forceFill($request->all())->save();

		return response()->admin($model);
	}

	/**
	 * @path /api/system/user/1
	 */
	public function show(Request $request, $id)
	{
		$model = User::findOrFail($id);

		return response()->admin($model);
	}

	public function update(Request $request, $id)
	{
		$model = User::findOrFail($id);

		$data = $request->all();
		unset($data['role_ids']);
		$model->forceFill($data)->save();

		return response()->admin($model);
	}

	public function destroy(Request $request, $id)
	{

	}
}
